using System;

namespace QntPlatform.Strategy.CmdCtrl
{
    /// <summary>
    /// 跟踪止盈
    /// </summary>
    public class TrailingProfit : CmdHandlePart
    {
        /// 止盈回撤率
        public decimal profitSlideRate { get; set; }=0.01m;
        /// 止盈率
        public decimal profitRate { get; set; }
        //通过止盈价格设置止盈率
        public decimal SetProfitRate(decimal price){
            profitRate= ISysFun.CalcProfitRate(price,Data.InPrice,Data.CloseDirection==SideDirection.CloseBuy);
            return profitRate;
        }
        public TrailingProfit(IStrategy parent, TrailingProfitData data,decimal _profitSlideRate=0.001m,decimal _profitRate=0.005m) : base(parent)
        {
            profitSlideRate= _profitSlideRate;
            profitRate= _profitRate;
            Data = data;
        }
        public TrailingProfitData Data { get; internal set; }
        /// 滑动止盈
        public bool Execute(Ticker tck)
        {
            if (Data.Amount<=0)
            {
                log.Info("小于0的仓位,空处理止盈",Data);
                return true;
            }
            var nowRate = ISysFun.CalcProfitRate(tck.Last, Data.InPrice,Data.CloseDirection==SideDirection.CloseBuy);
            if (nowRate > Data.topProfitRate)
            {
                Data.topProfitRate = nowRate;
                return false;
            }
            if (Data.topProfitRate < profitRate)
                return false;
            if ((Data.topProfitRate - nowRate) >= Data.topProfitRate * profitSlideRate) 
            {
                log.Debug("跟踪止盈执行",Data);
               // execTrade(Data.CloseDirection, Data.Amount,Data);
                Exchange.CreateOrder(Data.Amount, Data.CloseDirection, info: new Db.LogInfo() { Info2 = "跟踪止盈,市价:" + tck.Buy ,ParentActId=Data.SourceOrderId+""});
                return true;
            }
            return false;
        }
        public class TrailingProfitData
        {
            private string sid;

            public IConvertible SourceOrderId { get; set; }

            public decimal InPrice { get; set; }
            public decimal topProfitRate { get; internal set; }
            public decimal Amount { get; set; }
            public SideDirection CloseDirection { get; set; }
            public string Sid { get => sid; set => sid = value+GetHashCode(); }
        }

    }
}
